package com.qymerge.manage.base.service.impl;

import com.qymerge.manage.base.dao.*;
import com.qymerge.manage.base.ro.*;
import com.qymerge.manage.base.service.IMetaBudgetGLService;
import com.qymerge.manage.core.bean.ActionResultRO;
import com.qymerge.manage.core.bean.DataTableRO;
import com.qymerge.manage.core.bean.PageRequest;
import com.qymerge.manage.core.utils.ReadExcelBudgetUtil;
import com.qymerge.manage.core.utils.ReadExcelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: MetaProfitReportItemServiceImpl</p>
 * <p>Description: 利润表报表项目配置</p>
 *
 * @author Xiao
 * @date 2025/4/29 18:43
 * @version 1.0.0
 */
@Service
public class MetaBudgetGLServiceImpl implements IMetaBudgetGLService {

    @Autowired
    private IMetaBudgetGLDao metaBudgetGLDao;
    @Autowired
    private IMetaBudgetDao metaBudgetDao;
    @Autowired
    private IMetaCompanyDao metaCompanyDao;
    @Autowired
    private IMetaPeriodDao metaPeriodDao;
    @Autowired
    private IMetaAccountViewDao metaAccountViewDao;

    /**
     * 查询
     *
     * @param ro
     * @param pageRequest
     * @return
     */
    @Override
    public DataTableRO list(MetaBudgetGLRO ro, PageRequest pageRequest) {
        List<MetaBudgetGLRO> list = metaBudgetGLDao.list(ro, pageRequest);
        DataTableRO dataTableRO = new DataTableRO();
        int allCount = metaBudgetGLDao.total(ro);
        int pageSize = pageRequest.getSize();
        dataTableRO.setAll_count(allCount);
        dataTableRO.setList(list);
        dataTableRO.setCurrent_page(pageRequest.getPage());
        dataTableRO.setPage_size(pageSize);
        int allPage = (allCount % pageSize == 0 ? allCount / pageSize : allCount / pageSize + 1);
        dataTableRO.setAll_page(allPage);
        return dataTableRO;
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public MetaBudgetGLRO detail(Long id) {
        MetaBudgetGLRO profitReportItemDaoOne = metaBudgetGLDao.findOne(id);
        return profitReportItemDaoOne;
    }

    /**
     *
     * @param ro
     * @return
     */
    @Override
    public ActionResultRO save(MetaBudgetGLRO ro) {
        // 获取主表信息
        MetaBudgetRO searchBudgetRO = metaBudgetDao.findOne(ro.getBudgetId());
        if (searchBudgetRO != null) {
            ro.setInternalCompanyId(searchBudgetRO.getInternalCompanyId());    // 关联公司
            ro.setPeriodYear(searchBudgetRO.getPeriodYear());
            ro.setGroupAccountViewCode(ro.getAccountViewCode());
        }
        int rn = 0;
        MetaBudgetGLRO searchMetaBudgetGLRO = metaBudgetGLDao.findOneByYearMonthCode(ro.getBudgetId(), ro.getPeriodYear(), ro.getPeriodMonth(), ro.getAccountViewCode());
        if (ro.getId() == 0 && searchMetaBudgetGLRO == null) {
            rn = metaBudgetGLDao.insert(ro);
        } else {
            ro.setId(searchMetaBudgetGLRO.getId());
            rn = metaBudgetGLDao.update(ro);
        }
        return new ActionResultRO(rn, ro.getId() == 0 ? "保存成功" : "修改成功", ro.getId() == 0 ? "保存失败" : "修改失败");
    }

    @Override
    public ActionResultRO delete(Long[] ids) {
        int rn = metaBudgetGLDao.remove(Arrays.asList(ids));
        return new ActionResultRO(true, "删除" + rn +"成功", "删除" + rn +"失败");
    }

    @Override
    public ActionResultRO importData(MultipartFile multipartFile, Long BudgetId) {
        StringBuffer tip = new StringBuffer("导入结果：<br/>");
        ReadExcelUtil readExcelUtil = new ReadExcelUtil();
        List<String[][]> datas = null;
        try {
            datas = readExcelUtil.readByStream(multipartFile.getInputStream(), 2, multipartFile.getOriginalFilename());
            if (org.springframework.util.CollectionUtils.isEmpty(datas)) {
                return new ActionResultRO(false, "execl数据为空");
            }
            String[][] data = datas.get(0);

            Long budgetId= BudgetId;
            String internalCompanyId = "";

            String accountViewCode= "";
            String accountViewName= "";
            String groupAccountViewCode= "";

            BigDecimal amount = BigDecimal.ZERO;

            Integer periodYear = 0;
            Integer periodMonth = 0;

            List<MetaBudgetGLRO> roNewList = new ArrayList<>();
            MetaBudgetGLRO ro = null;
            int rowNum = 1;        // 记录当前行
            int successNum = 0;    // 记录新增或者更新记录数
            for (String[] row : data) {
                rowNum++;


                internalCompanyId = row[0];
                accountViewCode= row[1];
                accountViewName= row[2];
                groupAccountViewCode= row[3];
                amount= BigDecimal.valueOf(Double.valueOf(row[4]));

                periodYear = Integer.valueOf(row[5]);
                periodMonth = Integer.valueOf(row[6]);

                if (StringUtils.isEmpty(budgetId + "")
                        || StringUtils.isEmpty(internalCompanyId)
                        || StringUtils.isEmpty(accountViewCode)
                        || StringUtils.isEmpty(groupAccountViewCode)
                        || StringUtils.isEmpty(amount+"")
                ) {
                    tip.append("第").append(rowNum).append("行：部分数据为空，不予新增<br/>");
                    continue;
                }
                MetaCompanyRO companyRO = metaCompanyDao.findOne(internalCompanyId);
                if (companyRO == null) {
                    tip.append("第").append(rowNum).append("行：关联公司不存在，不予新增<br/>");
                    continue;
                }
//                MetaPeriodRO periodRO = metaPeriodDao.findOne(periodId);
//                if (periodRO == null) {
//                    tip.append("第").append(rowNum).append("行：关联会计期间不存在，不予新增<br/>");
//                    continue;
//                }
                MetaAccountViewRO accountViewRO = metaAccountViewDao.findOne(accountViewCode);
                if (accountViewRO == null) {
                    tip.append("第").append(rowNum).append("行：关联科目不存在，不予新增<br/>");
                    continue;
                }

                MetaAccountViewRO groupAccountViewRO = metaAccountViewDao.findOne(groupAccountViewCode);
                if (groupAccountViewRO == null) {
                    tip.append("第").append(rowNum).append("行：关联科目代码（集团）不存在，不予新增<br/>");
                    continue;
                }

                ro = new MetaBudgetGLRO(budgetId, internalCompanyId, accountViewCode, accountViewName, groupAccountViewCode, amount, periodYear, periodMonth);
                roNewList.add(ro);
            }

            if (tip.toString().equals("导入结果：<br/>")) {
                for (MetaBudgetGLRO metaBudgetGLRO : roNewList) {
                    metaBudgetGLDao.insert(ro);
                    successNum++;
                }

                tip.append("成功新增记录：").append(successNum).append("条");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ActionResultRO(false, "导入失败");
        }

        return new ActionResultRO(true, tip.toString());
    }

    @Override
    public ActionResultRO importData2(MultipartFile multipartFile, Long BudgetId) {
        StringBuffer tip = new StringBuffer("导入结果-总账类：<br/>");
        ReadExcelBudgetUtil readExcelUtil = new ReadExcelBudgetUtil();
        Map<String,String[][]> datas = null;
        try {
            datas = readExcelUtil.readByStream(multipartFile.getInputStream(), 5, 1, multipartFile.getOriginalFilename());
            if (org.springframework.util.CollectionUtils.isEmpty(datas)) {
                return new ActionResultRO(false, "execl数据为空");
            }
            String[][] data = datas.get("general_ledger_datas");  // 总账
            if (ArrayUtils.isNotEmpty(data)) {
                Long budgetId = BudgetId;
                String internalCompanyId = "";

                String accountViewCode = "";
                String accountViewName = "";
                String groupAccountViewCode = "";

                BigDecimal amount = BigDecimal.ZERO;

                Integer periodYear = 0;
                Integer periodMonth = 0;

                List<MetaBudgetGLRO> roNewList = new ArrayList<>();
                int rowNum = 5;        // 记录当前行
                int successNum1 = 0;    // 记录新增或者更新记录数
                int successNum11 = 0;    // 记录新增或者更新记录数

                // 获取主表信息
                MetaBudgetRO budgetRO = metaBudgetDao.findOne(BudgetId);
                if (budgetRO != null) {
                    internalCompanyId = budgetRO.getInternalCompanyId();    // 关联公司
                    periodYear = budgetRO.getPeriodYear();          // 年
                }

                for (String[] row : data) {
                    rowNum++;

                    accountViewCode = row[0];
                    accountViewName = row[1];

                    groupAccountViewCode = accountViewCode;

                    MetaAccountViewRO accountViewRO = metaAccountViewDao.findOne(accountViewCode);
                    if (accountViewRO == null) {
                        tip.append("第").append(rowNum).append("行：关联科目不存在，不予新增<br/>");
                        continue;
                    }

                    int j = 2;
                    // 同一个产品增加12条数据
                    for (int i = 1; i <= 12; i++) {
                        if (StringUtils.isNotBlank(row[j])) {
                            amount = BigDecimal.valueOf(Double.valueOf(row[j]));
                        } else {
                            amount = BigDecimal.ZERO;
                        }
                        MetaBudgetGLRO ro = new MetaBudgetGLRO(budgetId, internalCompanyId, accountViewCode, accountViewName, groupAccountViewCode, amount, periodYear, i);
                        roNewList.add(ro);

                        j = j + 1;
                    }
                }

                if (tip.toString().equals("导入结果-总账类：<br/>")) {
                    for (MetaBudgetGLRO metaBudgetGLRO : roNewList) {
                        MetaBudgetGLRO searchMetaBudgetGLRO = metaBudgetGLDao.findOneByYearMonthCode(metaBudgetGLRO.getBudgetId(), metaBudgetGLRO.getPeriodYear(), metaBudgetGLRO.getPeriodMonth(), metaBudgetGLRO.getAccountViewCode());
                        if (searchMetaBudgetGLRO != null) {
                            metaBudgetGLRO.setId(searchMetaBudgetGLRO.getId());
                            metaBudgetGLDao.updateAmount(metaBudgetGLRO);
                            successNum11++;
                        } else {
                            metaBudgetGLDao.insert(metaBudgetGLRO);
                            successNum1++;
                        }
                    }
                    tip.append("成功更新记录：").append(successNum11).append("条<br/>");
                    tip.append("成功新增记录：").append(successNum1).append("条<br/>");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ActionResultRO(false, "导入失败");
        }

        return new ActionResultRO(true, tip.toString());
    }

}
